<template>
  <!-- 配置车管家dialog -->
  <a-modal
    title="配置车管家"
    v-model:visible="visible"
    unmount-on-close
    :on-before-ok="handleOk"
    @cancel="handleCancel"
    @close="handleCancel"
  >
    <card :title="form.siteName" :showDivider="form.carHousekeepList && form.carHousekeepList.length < 20">
      <a-scrollbar
        ref="scrollContainer"
        :outer-style="{ 'overflow-y': 'auto', 'overflow-x': 'hidden' }"
        style="max-height: 300px; overflow-y: auto; overflow-x: hidden"
        @scroll="scrollFn"
      >
        <page-form layout="vertical" class="overflow-x-hidden">
          <page-form-row :gutter="24">
            <page-form-item :label="`车管家-${index + 1}`" size="1/2" v-for="(_, index) in form?.carHousekeepList" :key="index">
              <StaffSelect
                popupContainer="body"
                ref="staffSelectRef"
                :carHousekeepList="form?.carHousekeepList"
                :isOpenCarHousekeep="carHousekeep.isOpenCarHousekeep"
                :index="index"
                :storeInfo="{ siteId: form.id }"
              />
            </page-form-item>
          </page-form-row>
        </page-form>
      </a-scrollbar>
    </card>
    <a-link class="select-none" v-if="form.carHousekeepList && form.carHousekeepList.length < 20" @click="addStoreFn">添加车管家</a-link>
  </a-modal>
</template>

<script setup lang="ts">
  import StaffSelect from '@/views/business/workOrder/car-steward/components/staff-select.vue'

  import { ref, nextTick } from 'vue'
  import { updateCarHousekeep } from '@/api/business/workorder'
  import { Message } from '@arco-design/web-vue'
  import { getCarHousekeepDetail } from '@/api/business/workorder'

  const visible = ref(false)
  const emits = defineEmits(['ok'])
  const form = ref<any>({})
  // 车管家模式
  const carHousekeep = ref({
    isOpenCarHousekeep: 0,
  })
  const scrollContainer = ref()
  const addStoreFn = () => {
    form.value.carHousekeepList.push({ staffId: undefined })
    // 添加车管家后滚动到最底部
    nextTick(() => {
      const container = scrollContainer.value.$el.querySelector('.arco-form')
      container && scrollContainer.value.scrollTop(container.scrollHeight)
    })
  }

  // 获取车管家详情
  const getStaffDetail = () => {
    getCarHousekeepDetail().then((res: any) => {
      carHousekeep.value = res.result
    })
  }

  const open = (record: any) => {
    console.log(record, 'record')
    visible.value = true
    form.value = record
    getStaffDetail()
  }

  const submit = () => {
    const carHousekeepList = form.value.carHousekeepList.map((item: any) => item.staffId)
    form.value.list = [{ siteId: form.value.id, carHousekeepList }]
    form.value.isOpenCarHousekeep = carHousekeep.value.isOpenCarHousekeep

    return new Promise<boolean>((resolve) => {
      updateCarHousekeep(form.value)
        .then((res: any) => {
          if (res.code == 200) {
            Message.success('保存成功')
            emits('ok')
            resolve(true)
          }
        })
        .finally(() => {
          resolve(false)
        })
    })
  }

  // 校验
  const validateFn = () => {
    // 校验
    form.value.errSiteIdList = []
    let useable_count = 0
    form.value.carHousekeepList.forEach((item: any) => {
      if (item.staffId) {
        useable_count++
      }
      if (item.staffStatusName) {
        useable_count--
        if (item.staffStatusName == '选择重复，请重新选择') {
          useable_count = -99
        }
      }
    })
    if (useable_count <= 0) {
      // 判断是否是新增
      if (form.value.id) {
        form.value.errSiteIdList.push(form.value.id)
      } else {
        // 拦截不配置车管家
        form.value.errSiteIdList.push(1)
      }
    }
  }

  const handleOk = () => {
    // 校验
    if (carHousekeep.value.isOpenCarHousekeep === 1) {
      validateFn()
      // 开启再校验
      if (carHousekeep.value.isOpenCarHousekeep && form.value.errSiteIdList.length > 0) {
        Message.warning('请检查配置车管家')
        return false
      }

      return submit()
    } else {
      return submit()
    }
  }

  // 滑动滚动条 控制下拉框的隐藏
  const staffSelectRef = ref(null)
  const scrollFn = () => {
    staffSelectRef.value.length && staffSelectRef.value.map((it) => it.popupVisibleFn())
  }

  const handleCancel = () => {
    visible.value = false
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped></style>
